package com.ccteam.fluidmusic.ui.search

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import com.ccteam.fluidmusic.NavAlbumDirections
import com.ccteam.fluidmusic.databinding.FragmentSearchResultAlbumBinding
import com.ccteam.fluidmusic.view.adapters.AlbumListItemAdapter
import com.ccteam.fluidmusic.view.adapters.ArtistAlbumListAdapter
import com.ccteam.fluidmusic.view.adapters.paging.CustomLoadStateAdapter
import com.ccteam.fluidmusic.ui.playlist.select.AddOnlineMediaFragment.Companion.RESULT_MOMENTS_TYPE_KEY
import com.ccteam.fluidmusic.ui.playlist.select.AddOnlineMediaFragment.Companion.TYPE_SEARCH
import com.ccteam.model.moment.MOMENT_SHARE_TYPE_ALBUM
import com.ccteam.shared.result.album.AlbumListItem
import com.ccteam.shared.result.moment.MomentListItem
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author Xiaoc
 * @since 2021/3/16
 */
@AndroidEntryPoint
class SearchAlbumResultFragment: Fragment() {

    private var _binding: FragmentSearchResultAlbumBinding? = null
    private val binding: FragmentSearchResultAlbumBinding get() = _binding!!

    private val homeSearchAlbumResultViewModel by viewModels<HomeSearchAlbumResultViewModel>()

    companion object {
        @JvmStatic
        fun newInstance(searchKey: String,type: Int): SearchAlbumResultFragment {
            return SearchAlbumResultFragment().apply {
                arguments = Bundle().apply {
                    putString(SEARCH_KEY, searchKey)
                    putInt("type", type)
                }
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentSearchResultAlbumBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val dataAdapter = ArtistAlbumListAdapter(callback)
        binding.rvAlbumList.adapter = dataAdapter.withLoadStateFooter(
            CustomLoadStateAdapter(dataAdapter,true){
                dataAdapter.retry()
            }
        )

        viewLifecycleOwner.lifecycleScope.launch {
            homeSearchAlbumResultViewModel.albumList.collectLatest {
                dataAdapter.submitData(it)
            }
        }

        viewLifecycleOwner.lifecycleScope.launch {
            dataAdapter.loadStateFlow.collectLatest { state ->
                binding.statusView.changeToLoadingStatus(state.refresh is LoadState.Loading)
                binding.statusView.changeToErrorStatus(state.refresh,
                    state.append.endOfPaginationReached && dataAdapter.itemCount < 1)
            }
        }

        binding.statusView.setRetryClickListener {
            dataAdapter.refresh()
        }
    }

    private val callback = object: AlbumListItemAdapter.AlbumListItemCallback{

        override fun onClickItem(view: View, albumItem: AlbumListItem) {
            if(homeSearchAlbumResultViewModel.type == TYPE_SEARCH){
                findNavController().navigate(
                    NavAlbumDirections.actionGlobalAlbumDetailFragment(
                        albumItem.albumId
                    ))
            } else {
                parentFragment?.setFragmentResult(RESULT_MOMENTS_TYPE_KEY, bundleOf(RESULT_MOMENTS_TYPE_KEY to MomentListItem.MomentShareItem(
                    albumItem.mediaId,MOMENT_SHARE_TYPE_ALBUM,albumItem.albumTitle
                    ,albumItem.artist,albumItem.albumArtUri
                )))
                findNavController().navigateUp()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }
}